// 随机文本弹窗 - 增强版：支持批量依次弹出、随机位置/颜色/大小
(function(){
  const textsEl = document.getElementById('texts');
  const bgColorEl = document.getElementById('bgColor');
  const textColorEl = document.getElementById('textColor');
  const fontSizeEl = document.getElementById('fontSize');
  const autoHideEl = document.getElementById('autoHide');
  
  const randomPosEl = document.getElementById('randomPos');
  const randomColorEl = document.getElementById('randomColor');
  const randomSizeEl = document.getElementById('randomSize');
  const popupCountEl = document.getElementById('popupCount');
  const intervalEl = document.getElementById('interval');
  const trajectoryEl = document.getElementById('trajectory');

  const showBtn = document.getElementById('showBtn');
  const burstBtn = document.getElementById('burstBtn');
  const stopBtn = document.getElementById('stopBtn');
  const clearAllBtn = document.getElementById('clearAllBtn');
  const importBtn = document.getElementById('importBtn');
  const exportBtn = document.getElementById('exportBtn');
  const parseJsonBtn = document.getElementById('parseJsonBtn');
  const fileInput = document.getElementById('fileInput');

  const container = document.getElementById('popupContainer');

  let popupIdCounter = 0;
  let burstIntervalId = null;
  let burstCount = 0;
  let trajectoryIndex = 0; // 轨迹索引

  // 随机颜色生成器
  function randomColor(){
    const hue = Math.floor(Math.random() * 360);
    const sat = 60 + Math.random() * 40; // 60-100%
    const light = 50 + Math.random() * 30; // 50-80%
    return `hsl(${hue}, ${sat}%, ${light}%)`;
  }

  // 随机文本颜色（保证可读性）
  function randomTextColor(){
    return Math.random() > 0.5 ? '#000' : '#fff';
  }

  // 从文本区域读取条目
  function getEntries(){
    const raw = textsEl.value || '';
    const lines = raw.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
    return lines;
  }

  // 随机抽取一条
  function pickRandom(){
    const items = getEntries();
    if(items.length === 0) return '✨ 随机弹窗 ✨';
    const idx = Math.floor(Math.random() * items.length);
    return items[idx];
  }

  // === 轨迹计算函数 ===
  
  // 根据选定的轨迹和索引计算位置
  function calculateTrajectoryPosition(trajectory, index, total){
    const progress = total > 1 ? index / (total - 1) : 0.5; // 0 到 1 的进度
    let left = 50, top = 50;
    
    switch(trajectory){
      case 'top-to-bottom':
        left = 50;
        top = 10 + progress * 80;
        break;
        
      case 'left-to-right':
        left = 10 + progress * 80;
        top = 50;
        break;
        
      case 'diagonal':
        left = 10 + progress * 80;
        top = 10 + progress * 80;
        break;
        
      case 'circle':
        const angle = progress * Math.PI * 2;
        left = 50 + Math.cos(angle) * 35;
        top = 50 + Math.sin(angle) * 35;
        break;
        
      case 'heart':
        // 心形参数方程（优化版）
        const t = progress * Math.PI * 2;
        // 使用标准心形曲线公式
        const x = 16 * Math.pow(Math.sin(t), 3);
        const y = 13 * Math.cos(t) - 5 * Math.cos(2*t) - 2 * Math.cos(3*t) - Math.cos(4*t);
        // 缩放、翻转和居中（y需要取反让心形正立，并向下移动一点）
        left = 50 + x * 1.5;
        top = 50 - y * 1.5 + 5; // 向下偏移5%让心形更居中
        break;
        
      case 'spiral':
        const spiralAngle = progress * Math.PI * 4; // 2圈
        const radius = progress * 40;
        left = 50 + Math.cos(spiralAngle) * radius;
        top = 50 + Math.sin(spiralAngle) * radius;
        break;
        
      case 'wave':
        left = 10 + progress * 80;
        top = 50 + Math.sin(progress * Math.PI * 4) * 20; // 波浪
        break;
        
      case 'center-out':
        const outAngle = (index % 8) * (Math.PI / 4); // 8个方向
        const outDist = Math.floor(index / 8) * 15 + 15;
        left = 50 + Math.cos(outAngle) * outDist;
        top = 50 + Math.sin(outAngle) * outDist;
        break;
        
      case 'corners':
        const corners = [
          {left: 15, top: 15},
          {left: 85, top: 15},
          {left: 85, top: 85},
          {left: 15, top: 85}
        ];
        const corner = corners[index % 4];
        const offset = Math.floor(index / 4) * 10;
        left = corner.left + (Math.random() - 0.5) * offset;
        top = corner.top + (Math.random() - 0.5) * offset;
        break;
        
      case 'random':
      default:
        left = 10 + Math.random() * 80;
        top = 10 + Math.random() * 80;
        break;
    }
    
    // 确保在屏幕范围内
    left = Math.max(5, Math.min(95, left));
    top = Math.max(5, Math.min(95, top));
    
    return {left, top};
  }

  // 创建并显示一个弹窗
  function createPopup(){
    const id = ++popupIdCounter;
    const text = pickRandom();
    
    // 获取设置
    const trajectory = trajectoryEl.value;
    const useRandomPos = randomPosEl.checked && trajectory === 'random';
    const useRandomColor = randomColorEl.checked;
    const useRandomSize = randomSizeEl.checked;
    const autoHideSec = Math.max(0.5, parseFloat(autoHideEl.value) || 3);
    
    // 随机样式
    let bg = bgColorEl.value || '#ffd966';
    let color = textColorEl.value || '#000';
    let fontSize = parseInt(fontSizeEl.value, 10) || 20;
    
    if(useRandomColor){
      bg = randomColor();
      color = randomTextColor();
    }
    
    if(useRandomSize){
      fontSize = 14 + Math.floor(Math.random() * 30); // 14-44px
    }
    
    // 计算位置（根据轨迹或随机）
    let left = 50, top = 50;
    if(trajectory === 'random' && useRandomPos){
      left = 10 + Math.random() * 80;
      top = 10 + Math.random() * 80;
    } else {
      const total = parseInt(popupCountEl.value, 10) || 5;
      const pos = calculateTrajectoryPosition(trajectory, trajectoryIndex, total);
      left = pos.left;
      top = pos.top;
      trajectoryIndex++;
    }
    
    // 创建弹窗元素
    const popup = document.createElement('div');
    popup.className = 'popup';
    popup.dataset.id = id;
    popup.style.left = `${left}%`;
    popup.style.top = `${top}%`;
    
    const content = document.createElement('div');
    content.className = 'popup-content';
    content.style.background = bg;
    content.style.color = color;
    
    const closeBtn = document.createElement('button');
    closeBtn.className = 'close';
    closeBtn.textContent = '×';
    closeBtn.setAttribute('aria-label', '关闭');
    closeBtn.onclick = () => removePopup(popup);
    
    const textDiv = document.createElement('div');
    textDiv.className = 'popup-text';
    textDiv.textContent = text;
    textDiv.style.fontSize = `${fontSize}px`;
    
    content.appendChild(closeBtn);
    content.appendChild(textDiv);
    popup.appendChild(content);
    container.appendChild(popup);
    
    // 动画进入
    setTimeout(() => popup.classList.add('show'), 10);
    
    // 自动隐藏
    if(autoHideSec > 0){
      setTimeout(() => removePopup(popup), autoHideSec * 1000);
    }
    
    return popup;
  }

  // 移除弹窗（带动画）
  function removePopup(popup){
    if(!popup || !popup.parentNode) return;
    popup.classList.remove('show');
    popup.classList.add('hide');
    setTimeout(() => {
      if(popup.parentNode){
        popup.parentNode.removeChild(popup);
      }
    }, 300);
  }

  // 清除所有弹窗
  function clearAllPopups(){
    const popups = container.querySelectorAll('.popup');
    popups.forEach(p => removePopup(p));
  }

  // 停止批量弹出
  function stopBurst(){
    if(burstIntervalId){
      clearInterval(burstIntervalId);
      burstIntervalId = null;
    }
    burstBtn.disabled = false;
    stopBtn.disabled = true;
  }

  // 批量依次弹出
  function startBurst(){
    stopBurst(); // 先停止之前的
    
    const count = Math.max(1, parseInt(popupCountEl.value, 10) || 5);
    const interval = Math.max(0.1, parseFloat(intervalEl.value) || 0.8) * 1000;
    
    burstCount = 0;
    trajectoryIndex = 0; // 重置轨迹索引
    burstBtn.disabled = true;
    stopBtn.disabled = false;
    
    // 立即弹出第一个
    createPopup();
    burstCount++;
    
    // 定时弹出剩余的
    if(count > 1){
      burstIntervalId = setInterval(() => {
        if(burstCount >= count){
          stopBurst();
          return;
        }
        createPopup();
        burstCount++;
      }, interval);
    } else {
      stopBurst();
    }
  }

  // === JSON 导入导出功能 ===
  
  // 从文本数组设置到文本框
  function setTextsFromArray(arr){
    if(!Array.isArray(arr)){
      alert('⚠️ JSON格式错误：需要数组格式');
      return false;
    }
    const texts = arr.filter(t => typeof t === 'string' && t.trim()).map(t => t.trim());
    if(texts.length === 0){
      alert('⚠️ 没有找到有效的文本内容');
      return false;
    }
    textsEl.value = texts.join('\n');
    return true;
  }

  // 解析JSON（支持多种格式）
  function parseJsonContent(jsonStr){
    try {
      const data = JSON.parse(jsonStr);
      
      // 支持直接数组格式: ["text1", "text2"]
      if(Array.isArray(data)){
        return setTextsFromArray(data);
      }
      
      // 支持对象格式: {"messages": [...], "texts": [...], "items": [...]}
      if(typeof data === 'object' && data !== null){
        // 尝试常见的键名
        const possibleKeys = ['message', 'messages', 'texts', 'items', 'data', 'list', 'content', 'quotes', 'lines'];
        for(const key of possibleKeys){
          if(Array.isArray(data[key])){
            return setTextsFromArray(data[key]);
          }
        }
        
        // 如果对象的值都是字符串，提取所有值
        const values = Object.values(data);
        if(values.every(v => typeof v === 'string')){
          return setTextsFromArray(values);
        }
      }
      
      alert('⚠️ JSON格式不支持\n\n支持的格式:\n1. ["文本1", "文本2"]\n2. {"message": ["文本1", "文本2"]}\n3. {"messages": ["文本1", "文本2"]}');
      return false;
    } catch(e) {
      alert('⚠️ JSON解析失败: ' + e.message);
      return false;
    }
  }

  // 导入JSON文件
  function importFromFile(){
    fileInput.click();
  }

  fileInput.addEventListener('change', (e) => {
    const file = e.target.files[0];
    if(!file) return;
    
    const reader = new FileReader();
    reader.onload = (event) => {
      const content = event.target.result;
      if(parseJsonContent(content)){
        alert('✅ 成功导入 ' + getEntries().length + ' 条文本！');
      }
      fileInput.value = ''; // 重置input以便再次选择同一文件
    };
    reader.onerror = () => {
      alert('⚠️ 文件读取失败');
      fileInput.value = '';
    };
    reader.readAsText(file);
  });

  // 导出为JSON文件
  function exportToFile(){
    const entries = getEntries();
    if(entries.length === 0){
      alert('⚠️ 没有可导出的文本');
      return;
    }
    
    const jsonData = {
      messages: entries,
      exportDate: new Date().toISOString(),
      count: entries.length
    };
    
    const jsonStr = JSON.stringify(jsonData, null, 2);
    const blob = new Blob([jsonStr], {type: 'application/json'});
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = `popup-texts-${Date.now()}.json`;
    a.click();
    
    URL.revokeObjectURL(url);
    alert('✅ 已导出 ' + entries.length + ' 条文本！');
  }

  // 解析文本框中的JSON格式
  function parseJsonFromTextarea(){
    const content = textsEl.value.trim();
    if(!content){
      alert('⚠️ 文本框为空');
      return;
    }
    
    // 检查是否看起来像JSON
    if(!content.startsWith('[') && !content.startsWith('{')){
      alert('⚠️ 内容不是JSON格式\n\n请粘贴JSON格式的文本，例如:\n["文本1", "文本2"]');
      return;
    }
    
    if(parseJsonContent(content)){
      alert('✅ 成功解析 ' + getEntries().length + ' 条文本！');
    }
  }

  // 事件绑定
  showBtn.addEventListener('click', createPopup);
  burstBtn.addEventListener('click', startBurst);
  stopBtn.addEventListener('click', stopBurst);
  clearAllBtn.addEventListener('click', clearAllPopups);
  importBtn.addEventListener('click', importFromFile);
  exportBtn.addEventListener('click', exportToFile);
  parseJsonBtn.addEventListener('click', parseJsonFromTextarea);

  // 轨迹选择改变时，自动调整随机位置复选框
  trajectoryEl.addEventListener('change', () => {
    if(trajectoryEl.value !== 'random'){
      randomPosEl.checked = false;
    } else {
      randomPosEl.checked = true;
    }
  });

  // 随机位置复选框改变时，同步轨迹选择
  randomPosEl.addEventListener('change', () => {
    if(randomPosEl.checked){
      trajectoryEl.value = 'random';
    }
  });

  // 支持 ESC 键关闭所有弹窗
  document.addEventListener('keydown', (e) => {
    if(e.key === 'Escape'){
      clearAllPopups();
      stopBurst();
    }
  });

  // 初始化示例文本
  document.addEventListener('DOMContentLoaded', () => {
    if(!textsEl.value.trim()){
      textsEl.value = "🎉 惊喜！\n✨ 你太棒了！\n💖 今天也要开心哦~\n🌈 好运连连！\n⭐ 继续加油！\n🎈 元气满满！\n🍀 幸运儿~\n🎁 送你一个祝福！";
    }
    stopBtn.disabled = true;
  });
})();